import os
import time
import schedule
import argparse

from domains.Console import MumuConsole
from domains.Checker import Checker
from domains.Notifier import Notifier
from utils.funcs import generate_kb_info_from_html
from utils.lg import logger


parser = argparse.ArgumentParser(description="Automatic check-in scripts")
parser.add_argument('--week', '-w', type=int, help="The current number of weeks", required=True)
parser.add_argument('--delay', '-d', type=float,
                    help="The wait delay after each check-in operation is executed", default=5.0)

args = parser.parse_args()

# 签到工具
mm = MumuConsole()
notifier = Notifier()
checker = Checker(mm, notifier)

# 周数
week = args.week
# 初始化课表
kb = {}
for ff in os.scandir(r"data\htmls"):
    if ff.is_file() and ff.name.endswith(".html"):
        kkb_info = generate_kb_info_from_html(ff.path)
        try:
            # 文件名规范: kb_下标.html，如: kb_0.html
            kb_index = int(ff.name.split(".")[-2].split("_")[-1])
        except ValueError:
            raise ValueError(f"文件命名不规范: {ff.name}")
        # 第week周的课表
        kb[kb_index] = kkb_info[str(week)]


def update_week():
    """更新周数"""
    global week
    week += 1
    logger.info(f"更新周数, 当前周数为: {week}")


def update_kb():
    """更新本周的课表"""
    for f in os.scandir(r"data\htmls"):
        if f.is_file() and f.name.endswith(".html"):
            kb_info = generate_kb_info_from_html(f.path)
            try:
                # 文件名规范: kb_下标.html，如: kb_0.html
                kb_index = int(f.name.split(".")[-2].split("_")[-1])
            except ValueError:
                raise ValueError(f"文件命名不规范: {f.name}")
            # 第week周的课表
            kb[kb_index] = kb_info[week]
    logger.info("成功更新课表")


def set_tasks():
    # 清空之前的任务
    schedule.clear()
    # 设定新任务
    for index, kb_this_week in kb.items():
        kb_this_week: dict[str, list[list[str]]]
        for xq, course_list in kb_this_week.items():
            for t, name in course_list:
                if xq == "1":
                    schedule.every().monday.at(t).do(checker.run, index, name, args.delay)
                elif xq == "2":
                    schedule.every().tuesday.at(t).do(checker.run, index, name, args.delay)
                elif xq == "3":
                    schedule.every().wednesday.at(t).do(checker.run, index, name, args.delay)
                elif xq == "4":
                    schedule.every().thursday.at(t).do(checker.run, index, name, args.delay)
                elif xq == "5":
                    schedule.every().friday.at(t).do(checker.run, index, name, args.delay)
                elif xq == "6":
                    schedule.every().saturday.at(t).do(checker.run, index, name, args.delay)
                elif xq == "7":
                    schedule.every().sunday.at(t).do(checker.run, index, name, args.delay)
    # 每周一00:01重新设置任务
    schedule.every().monday.at("00:01").do(update_week)
    schedule.every().monday.at("00:02").do(update_kb)
    schedule.every().monday.at("00:03").do(set_tasks)


if __name__ == '__main__':
    set_tasks()
    while True:
        schedule.run_pending()
        time.sleep(60)
